const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const { Users, Menus } = require('../models')
const { SussessModel, FailModel } = require('../extend/helper')
const { SECRET } = require('../config/index')

router.prefix('/v1')

// 注册接口
router.post('/register', async (ctx, next) => {
  const { username, password, avatar, realname } = ctx.request.body;
  const data = await Users.find({username})
  // 用户名字注册重复
  if (!data.length) {
    const res = await Users.create({ username, password, avatar, realname })
    ctx.body = new SussessModel('success', res, 200)
  } else {
    ctx.body = new FailModel('用户已经存在')
  }
})

router.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body;
  const result = await Users.findOne({ username, password })
  console.log('result:', result)
  if (result) {
    let token = jwt.sign({ id: result._id  }, SECRET, { expiresIn: '1h' })
    ctx.body = new SussessModel('success', token)
  } else {
    ctx.body = new FailModel('登陆失败')
  }
})

router.get('/userInfo', async (ctx, next) => {
  console.log('ctx,:', ctx.app.helper)
  const { authorization } = ctx.request.headers;
  let token = authorization.replace('Bearer ', '')
  const data = jwt.verify(token, SECRET)
  const { avatar, role, username } = await Users.findOne({ _id: data.id })
  const menus = await Menus.find();
  ctx.body = new ctx.app.helper.SussessModel({ avatar, role, username, menus}, 200)
})


// 添加路由信息功能；
router.post('/addMenu', async (ctx, next) => {
  const { hidden,
    icon,
    id,
    level,
    name,
    parentId,
    sort, } = ctx.request.body;
  const data = await Menus.create({hidden,
    icon,
    id,
    level,
    name,
    parentId,
    sort,})
  ctx.body = { data }
})



module.exports = router
